% plot_pareto_front_from_csv.m
% 从CSV文件读取帕累托前沿数据并绘制散点图
function plot_pareto_front_from_csv(csv_file, output_dir, case_name)
    % 读取CSV数据
    data = readtable(csv_file);
    
    % 提取数据
    times = data.time;
    spills = data.spill;
    solution_ids = data.solution_id;
    
    % 找到关键解
    [min_time, min_time_idx] = min(times);
    [min_spill, min_spill_idx] = min(spills);
    
    % 计算最优折中解（归一化距离最小）
    norm_times = (times - min_time) / (max(times) - min_time + eps);
    norm_spills = (spills - min_spill) / (max(spills) - min_spill + eps);
    distances = sqrt(norm_times.^2 + norm_spills.^2);
    [~, min_dist_idx] = min(distances);
    
    % 创建图形
    fig = figure('Name', '帕累托最优前沿 (Pareto Front)', 'Position', [100, 100, 800, 600]);
    hold on;
    
    % 绘制所有前沿解
    scatter(times, spills, 60, 'b', 'filled', 'DisplayName', '帕累托前沿解');
    
    % 高亮显示关键解
    scatter(times(min_time_idx), spills(min_time_idx), 120, 'r', 'filled', ...
            'DisplayName', sprintf('最优时间解 (ID:%d)', solution_ids(min_time_idx)));
    scatter(times(min_spill_idx), spills(min_spill_idx), 120, 'g', 'filled', ...
            'DisplayName', sprintf('最优Spill解 (ID:%d)', solution_ids(min_spill_idx)));
    scatter(times(min_dist_idx), spills(min_dist_idx), 120, 'm', 'p', 'filled', ...
            'DisplayName', sprintf('最优折中解 (ID:%d)', solution_ids(min_dist_idx)));
    
    % 添加解的编号
    for i = 1:length(times)
        text(times(i), spills(i), sprintf(' %d', solution_ids(i)), ...
             'FontSize', 8, 'Color', 'k', 'HorizontalAlignment', 'left');
    end
    
    % 设置图表属性
    title(['帕累托最优前沿 - ' case_name], 'FontSize', 14, 'FontWeight', 'bold');
    xlabel('总执行时间 (Total Execution Time)', 'FontSize', 12);
    ylabel('总额外数据搬运量 (Total Spill Volume)', 'FontSize', 12);
    grid on;
    legend('show', 'Location', 'best', 'FontSize', 10);
    
    % 美化图表
    set(gca, 'FontSize', 11);
    set(gca, 'GridAlpha', 0.3);
    box on;
    
    hold off;
    
    % 保存图表
    png_file = fullfile(output_dir, [case_name '_pareto_front.png']);
    fig_file = fullfile(output_dir, [case_name '_pareto_front.fig']);
    
    saveas(fig, png_file);
    saveas(fig, fig_file);
    
    fprintf('  帕累托前沿图已保存至: %s\n', png_file);
    
    % 输出关键解信息
    fprintf('  关键解信息:\n');
    fprintf('    最优时间解: ID=%d, Time=%.2f, Spill=%.0f\n', ...
            solution_ids(min_time_idx), times(min_time_idx), spills(min_time_idx));
    fprintf('    最优Spill解: ID=%d, Time=%.2f, Spill=%.0f\n', ...
            solution_ids(min_spill_idx), times(min_spill_idx), spills(min_spill_idx));
    fprintf('    最优折中解: ID=%d, Time=%.2f, Spill=%.0f\n', ...
            solution_ids(min_dist_idx), times(min_dist_idx), spills(min_dist_idx));
    
    close(fig);
end



